/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package view;

import com.sun.lwuit.Command;
import com.sun.lwuit.Component;
import com.sun.lwuit.Form;
import com.sun.lwuit.Font;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.BoxLayout;
import com.sun.lwuit.list.DefaultListCellRenderer;
import java.util.Hashtable;
import java.util.Vector;
import core.MainOne;
import utils.XMLParser;
import view.additional.ThumbList;

/**
 *
 * @author Kvest
 */
public class DynamicForm extends Form implements ActionListener
{
    private Vector item_actions;
    private ThumbList list = null;
    private Command list_select = null;
    private Hashtable command_actions;

    public DynamicForm(String xml)
    {
        super(XMLParser.getParamString(xml,"title"));

        setLayout(new BoxLayout(BoxLayout.Y_AXIS));

        item_actions = new Vector();
        command_actions = new Hashtable();

        //Компоненты формы
        Vector xmls = XMLParser.getTags(xml, "component");
        for (int i = 0; i < xmls.size(); ++i)
        {
            parseComponent((String)xmls.elementAt(i));
        }

        //Команды формы
        xmls = XMLParser.getTags(xml, "command");
        for (int i = 0; i < xmls.size(); ++i)
        {
            parseCommand((String)xmls.elementAt(i));
        }

        addCommandListener(this);
    }

    private void parseComponent(String xml)
    {
        String type = XMLParser.getParamString(xml, "type");

        if (type.equals("list"))
        {
            parseList(xml);
        }
    }

    private void parseList(String xml)
    {
        setScrollable(false);
        list = new ThumbList();
        list.setFixedSelection(ThumbList.FIXED_NONE_CYCLIC);
        list.getStyle().setPadding(Component.BOTTOM, 0);
        list.getStyle().setPadding(Component.TOP, 0);
        DefaultListCellRenderer dlcr = new DefaultListCellRenderer();
        dlcr.setShowNumbers(false);

        //padding 
        int padding;
        try
        {
            padding = Integer.parseInt(XMLParser.getParamString(xml,"padding"));
        }catch(Exception ex){padding = -1;}
        if (padding != -1)
        {
            dlcr.getStyle().setPadding(Component.BOTTOM, padding);
            dlcr.getStyle().setPadding(Component.TOP, 0);
            dlcr.getSelectedStyle().setPadding(Component.BOTTOM, padding);
            dlcr.getSelectedStyle().setPadding(Component.TOP, 0);
        }

        list.setListCellRenderer(dlcr);
        
        //Цвет, размер шрифта и т.д
        try
        {
            int forntcolor = Integer.parseInt(XMLParser.getParamString(xml,"forntcolor"));
            dlcr.getStyle().setFgColor(forntcolor);
            getTitleStyle().setFgColor(forntcolor);
           //ToDo color of command font
        }catch(Exception ex){}
        try
        {
            int bgcolor = Integer.parseInt(XMLParser.getParamString(xml,"bgcolor"));
            getStyle().setBgColor(bgcolor);
        }catch(Exception ex){}

        String fontsizeStr = XMLParser.getParamString(xml,"fontsize");
        int fontsize = Font.SIZE_MEDIUM;

        if (fontsizeStr.equals("large"))
        {
            fontsize = Font.SIZE_LARGE;
        }
        else if (fontsizeStr.equals("small"))
        {
            fontsize = Font.SIZE_SMALL;
        }
        Font font = Font.createSystemFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, fontsize);
        dlcr.getStyle().setFont(font);

        Vector xmlItems = XMLParser.getTags(xml, "item");

        //Очищаем вектор событий
        item_actions.removeAllElements();

        String action,change;
        for (int i = 0; i < xmlItems.size(); ++i)
        {
            ListItem listItem = new ListItem(XMLParser.getStringElement((String)xmlItems.elementAt(i),"item"));
            list.addItem(listItem);

            
            if (!XMLParser.getParamString((String)xmlItems.elementAt(i), "next_form").equals(""))
            {
                action = Long.toString(System.currentTimeMillis());
                final String next_form = XMLParser.getParamString((String)xmlItems.elementAt(i), "next_form");
                ActionManager.getManager().addAction(action, new ActionManager.ActionCallback()
                {
                    public void action()
                    {
                        DynamicForm form =  ViewManager.getViewManager().getForm(next_form);

                        if (form != null)
                        {
                            MainOne.getMainOne().setPrev(form);
                            form.show();
                        }
                    }
                });
                item_actions.addElement(action);
            }
            else
            {
                action = XMLParser.getParamString((String)xmlItems.elementAt(i), "action");
                listItem.action = action;
                item_actions.addElement(action);
            }
            change = XMLParser.getParamString((String)xmlItems.elementAt(i), "change");
            if (!change.equals(""))
            {
                final ListItem label = (ListItem)list.getModel().getItemAt(i);

                ActionManager.ItemChangeCallback callback = new ActionManager.ItemChangeCallback()
                {
                    public void change(String text)
                    {
                        label.setText(text);
                        list.repaint();
                    }
                };

                ActionManager.getManager().addItemChangeCallback(change, listItem.getText() ,callback);
            }
        }

        String selectCommandXML = XMLParser.getElement(xml, "selectcommand");
        if (!selectCommandXML.equals(""))
        {
            list.setSelectCommandText(XMLParser.getStringElement(selectCommandXML,"selectcommand"));

            list.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent evt)
                {
                    //ToDo
                    System.out.println("list action");
                }
            });
        }
        else
        {
             list.setSelectCommandText("");
        }
        
        addComponent(list);
    }

    private void parseCommand(String xml)
    {
        Command c = new Command(XMLParser.getStringElement(xml,"command"));
        addCommand(c);

        String type = XMLParser.getParamString(xml, "type");
        if (type.equals("list_select"))
        {
            list_select = c;
        }
        else
        {
            if (!XMLParser.getParamString(xml,"next_form").equals(""))
            {
                String com_action = Long.toString(System.currentTimeMillis());
                final String next_form = XMLParser.getParamString(xml, "next_form");
                ActionManager.getManager().addAction(com_action, new ActionManager.ActionCallback()
                {
                    public void action()
                    {
                        DynamicForm form =  ViewManager.getViewManager().getForm(next_form);

                        if (form != null)
                        {
                            MainOne.getMainOne().setPrev(form);
                            form.show();
                        }
                    }
                });
                command_actions.put(c, com_action);
            }
            else
            {
                String com_action = XMLParser.getParamString(xml,"com_action");
                command_actions.put(c, com_action);
            }
        }
    }

    public void deleteListItemByAction(String action) {
        if (list != null) {
            for (int i = list.getModel().getSize() - 1; i >= 0 ; --i) {
                if (action.equals(((ListItem)list.getModel().getItemAt(i)).action)) {
                    list.getModel().removeItem(i);
                }
            }
        }
    }
    
    public void actionPerformed(ActionEvent evt)
    {
        Command c = evt.getCommand();
        if (c == list_select)
        {
            if (list != null)
            {
                //Определяем имя обработчика
                String sctionName = (String)item_actions.elementAt(list.getSelectedIndex());

                if (sctionName.equals(""))
                {
                    return;
                }
                
                //Получаем обработчик
                ActionManager.ActionCallback callback = ActionManager.getManager().getAction(sctionName);

                //Если получили обработчик - вызываем
                if (callback != null)
                {
                    callback.action();
                }    
            }
        }
        else
        {
            if (command_actions.containsKey(c))
            {
                //Определяем имя обработчика
                String com_action = (String)command_actions.get(c);

                 //Получаем обработчик
                ActionManager.ActionCallback callback = ActionManager.getManager().getAction(com_action);

                //Если получили обработчик - вызываем
                if (callback != null)
                {
                    callback.action();
                }
            }
        }
    }
}
